package com.controller;

import com.common.Result;
import com.constants.ResultCode;
import com.mapper.UserMapper;
import com.pojo.dto.LoginDto;
import com.pojo.dto.RegisterDto;
import com.pojo.dto.UserDto;
import com.service.IUserService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author : 杨世博
 * @date: Created in 9:49 2023/6/3
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户接口")
@Slf4j
public class UserController {

    @Autowired
    IUserService userService;

    @PostMapping("/login")
    public Result<UserDto> login(@RequestBody LoginDto loginDto){
        System.out.println(loginDto);
        UserDto userDto = userService.login(loginDto);
        System.out.println(loginDto);
        return Result.judge(userDto != null, userDto, ResultCode.USER_CREDENTIALS_ERROR);
    }

    @PostMapping("/register")
    public Result<UserDto> register(@RequestBody RegisterDto registerDto){
        userService.register(registerDto);
        return Result.success();
    }

    @PostMapping("/uploadImg")
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file){
        String fileName = file.getOriginalFilename();
        System.out.println("111"+fileName);
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String filePath = "D://picture//shopping//";
        fileName =UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("http://localhost:8080/static/"+fileName);

        return Result.success("http://localhost:8080/static/"+fileName);
    }
}
